<?php

namespace app\api\model\user;

use app\api\model\order\Order;
use app\common\model\settings\Region;
use app\common\model\user\UserAddress as UserAddressModel;
use think\facade\Db;

/**
 * 用户收货地址模型
 */
class UserAddress extends UserAddressModel
{
    /**
     * 隐藏字段
     */
    protected $hidden = [
        'app_id',
        'create_time',
        'update_time'
    ];

    /**
     * 获取列表
     */
    public function getList($user_id, $getDic = false)
    {
        if($getDic){
            return $this->where('user_id', '=', $user_id)->select()->each(function ($item, $key) {
                $item->delivery = Order::checkAddressDelivery($item, 0, 0, 0, 2);
            });
        }
        return $this->where('user_id', '=', $user_id)->select();
    }

    /**
     * 新增收货地址
     */
    public function add($user, $data)
    {
        // 添加收货地址
        $this->startTrans();
        try {
            $address_id = $this->insertGetId([
                'name' => $data['name'],
                'phone' => $data['phone'],
                'province_id' => $data['province_id'],
                'city_id' => $data['city_id'],
                'region_id' => $data['region_id'],
                'detail' => $data['detail'],
                'house_number' => $data['house_number']??'',
                'longitude' => $data['longitude'],
                'latitude' => $data['latitude'],
                'district' => ($data['region_id'] === 0 && !empty($region[2])) ? $region[2] : '',
                'user_id' => $user['user_id'],
                'app_id' => self::$app_id
            ]);
            // 设为默认收货地址
            !$user['address_id'] && $user->save(['address_id' => $address_id]);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }

    /**
     * 编辑收货地址
     */
    public function edit($data)
    {
        // 添加收货地址
//        $region = explode(',', $data['region']);
//        $province_id = Region::getIdByName($region[0], 1);
//        $city_id = Region::getIdByName($region[1], 2, $province_id);
//        $region_id = Region::getIdByName($region[2], 3, $city_id);
        $province_id = $data['province_id'];
        $city_id = $data['city_id'];
        $region_id = $data['region_id'];
        return $this->save([
                'name' => $data['name'],
                'phone' => $data['phone'],
                'province_id' => $province_id,
                'city_id' => $city_id,
                'region_id' => $region_id,
                'detail' => $data['detail'],
                'house_number' => $data['house_number']??'',
                'longitude' => $data['longitude'],
                'latitude' => $data['latitude'],
                'district' => ($region_id === 0 && !empty($region[2])) ? $region[2] : '',
            ]) !== false;
    }

    /**
     * 设为默认收货地址
     */
    public function setDefault($user)
    {
        // 设为默认地址
        return $user->save(['address_id' => $this['address_id']]);
    }

    /**
     * 删除收货地址
     * @return bool
     * @throws \Exception
     */
    public function remove($user)
    {
        // 查询当前是否为默认地址
        $user['address_id'] == $this['address_id'] && $user->save(['address_id' => 0]);
        return $this->delete();
    }

    /**
     * 收货地址详情
     */
    public static function detail($user, $address_id)
    {
        $data =[];
        $user_id = $user['user_id'];
        $where = ['user_id' => $user_id, 'address_id' => $address_id];
        $data = (new static())->where($where)->find();

        if(!$data){
            $where = [];
            $address_id = $user['address_id']; //默认地址id
            $where = ['user_id' => $user_id, 'address_id' => $address_id];
            $data = (new static())->where($where)->find();
            if(!$data){
                $where = [];
                $where = ['user_id' => $user_id];
                $data = (new static())->where($where) -> order('address_id desc') ->find();
            }
        }
        return $data;
    }

    /**
     * 查询用户地址中距离最近的一条
     * @param $where
     * @param $user_id
     * @return mixed
     * @Author joey
     * @date 2024/3/15 15:24
     * @Date Mr.Z 20240531 调整不需要城市
     */
    public function getMinDistance($where, $user_id)
    {
        if(isset($where['city_id'])&&$where['city_id']>0){
            return Db::query("SELECT
                         s.*,
                        (st_distance (point (s.longitude, s.latitude), point(?, ?) ) * 111195) as distance
                        FROM
                        jjjshop_user_address as s
                        WHERE s.user_id = ? AND s.city_id = ?
                        ORDER BY distance limit 1", [$where['longitude'], $where['latitude'], $user_id, $where['city_id']]);
        }else{
            return Db::query("SELECT
                         s.*,
                        (st_distance (point (s.longitude, s.latitude), point(?, ?) ) * 111195) as distance
                        FROM
                        jjjshop_user_address as s
                        WHERE s.user_id = ? 
                        ORDER BY distance limit 1", [$where['longitude'], $where['latitude'], $user_id]);
        }
    }

}
